<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="60%">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="合同编号" prop="contractNumber">
            <el-input v-model="formData.contractNumber" placeholder="请输入合同编号" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="签订企业" prop="signingCompany">
            <el-input v-model="formData.signingCompany" placeholder="请输入签订企业名称" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="对方企业" prop="counterpartyCompany">
            <el-input v-model="formData.counterpartyCompany" placeholder="请输入对方企业名称" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="合同标题" prop="contractTitle">
            <el-input v-model="formData.contractTitle" placeholder="请输入合同标题" />
          </el-form-item>
        </el-col>
        <!-- <el-col :span="8">
          <el-form-item label="签署人" prop="signatory">
            <el-input v-model="formData.signatory" placeholder="请输入签署人" />
          </el-form-item>
        </el-col> -->
        <el-col :span="8">
<!--          <el-form-item label="合同类型" prop="contractType">-->
<!--            <el-input v-model="formData.contractType" placeholder="请输合同类型" />-->
<!--          </el-form-item>-->

          <el-form-item label="合同类型" prop="contractType">
            <el-select v-model="formData.contractType" placeholder="请选择合同类型">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.OA_CONTRACT_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        
      </el-row>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="签订日期" prop="signingDate">
            <el-date-picker
              v-model="formData.signingDate"
              type="date"
              value-format="YYYY-MM-DD"
              format="YYYY-MM-DD"
              placeholder="选择签订日期"
              class="!w-240px"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="结束时间" prop="endDate">
            <el-date-picker
              v-model="formData.endDate"
              type="date"
              value-format="YYYY-MM-DD"
              format="YYYY-MM-DD"
              placeholder="选择合同结束时间"
              class="!w-240px"
            />
          </el-form-item>
        </el-col>
        
        
        <!-- <el-col :span="8">
          <el-form-item label="开始时间" prop="startDate">
            <el-date-picker
              v-model="formData.startDate"
              type="date"
              value-format="YYYY-MM-DD"
              format="YYYY-MM-DD"
              placeholder="选择合同开始时间"
              class="!w-240px"
            />
          </el-form-item>
        </el-col> -->
      </el-row>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="合同金额" prop="contractAmount">
            <el-input-number
              v-model="formData.contractAmount"
              :precision="2"
              :step="1000"
              :min="0"
              placeholder="请输入合同金额"
              class="!w-240px"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="付款日期" prop="paymentDate">
            <el-date-picker
              v-model="formData.paymentDate"
              type="date"
              value-format="YYYY-MM-DD"
              format="YYYY-MM-DD"
              placeholder="选择付款日期"
              class="!w-240px"
            />
          </el-form-item>
        </el-col>
<!--        <el-col :span="8">-->
<!--          <el-form-item label="附件路径" prop="files">-->
<!--            <el-input v-model="formData.files" placeholder="请输入附件路径" />-->
<!--          </el-form-item>-->
<!--        </el-col>-->
      </el-row>



      <!-- <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="特殊说明" prop="specialNotes">
            <el-input v-model="formData.specialNotes" placeholder="请输入特殊说明" type="textarea" />
          </el-form-item>
        </el-col>
      </el-row> -->

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="备注" prop="remarks">
            <el-input v-model="formData.remarks" placeholder="请输入备注" :rows="5" type="textarea" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-col :span="24">
        <el-form-item label="相关附件" >
          <OaFileManager :folderDisabled="true" :initial-file-ids="formData.files" @fileSelectSuccess="fileSelectScccess"  />
        </el-form-item>
      </el-col>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { InternalContractApi, InternalContractVO } from '@/api/oa/internalcontract'
import { TreeConfigApi, TreeConfigVO } from '@/api/oa/treeconfig'
import { handleTree } from '@/utils/tree'
import { DICT_TYPE, getStrDictOptions } from '@/utils/dict'

/** 内部合同信息 表单 */
defineOptions({ name: 'InternalContractForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const treeOptions = ref<TreeConfigVO[]>([]) // 树形选项
const formData = ref({
  id: undefined,
  contractNumber: undefined,
  signingCompany: undefined,
  counterpartyCompany: undefined,
  signatory: undefined,
  startDate: undefined,
  paymentDate: undefined,
  specialNotes: undefined,
  files: undefined,
  contractType: undefined,
  contractTitle: undefined,
  contractAmount: 0,
  signingDate: undefined,
  endDate: undefined,
  remarks: undefined,
  creatorName: undefined,
  updaterName: undefined,
})
const formRules = reactive({
  contractNumber: [{ required: true, message: '合同编号不能为空', trigger: 'blur' }],
  signingCompany: [{ required: true, message: '签订企业名称不能为空', trigger: 'blur' }],
  counterpartyCompany: [{ required: true, message: '对方企业名称不能为空', trigger: 'blur' }],
  // startDate: [{ required: true, message: '合同开始时间不能为空', trigger: 'blur' }],
  contractType: [{ required: true, message: '合同类型不能为空', trigger: 'change' }],
  contractTitle: [{ required: true, message: '合同标题不能为空', trigger: 'blur' }],
  contractAmount: [{ required: true, message: '合同金额不能为空', trigger: 'blur' }],
  signingDate: [{ required: true, message: '签订日期不能为空', trigger: 'blur' }],
  endDate: [{ required: true, message: '合同结束时间不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

const fileSelectScccess = (fileIds: string[]) => {
  formData.value.files = fileIds.join(',')
}

/** 获取树形数据 */
const getTreeOptions = async () => {
  try {
    const data = await TreeConfigApi.getTreeConfigList({
      configType: 'CONTRACT_CATEGORY' // 使用合同分类类型
    })
    treeOptions.value = handleTree(data)
  } catch (error) {
    console.error('获取合同分类树失败:', error)
  }
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 获取树形数据
  await getTreeOptions()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const data = await InternalContractApi.getInternalContract(id)
      // 转换时间格式
      if (data.startDate) data.startDate = formatDate(data.startDate)
      if (data.endDate) data.endDate = formatDate(data.endDate)
      if (data.signingDate) data.signingDate = formatDate(data.signingDate)
      if (data.paymentDate) data.paymentDate = formatDate(data.paymentDate)
      formData.value = data
    } finally {
      formLoading.value = false
    }
  }
}

/** 格式化日期为 YYYY-MM-DD */
const formatDate = (date: string | number | Date) => {
  if (!date) return ''
  const d = new Date(date)
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = { ...formData.value } as unknown as InternalContractVO
    // 转换时间格式为日期字符串
    if (data.startDate) data.startDate = data.startDate as unknown as Date
    if (data.endDate) data.endDate = data.endDate as unknown as Date
    if (data.signingDate) data.signingDate = data.signingDate as unknown as Date
    if (data.paymentDate) data.paymentDate = data.paymentDate as unknown as Date

    if (formType.value === 'create') {
      await InternalContractApi.createInternalContract(data)
      message.success(t('common.createSuccess'))
    } else {
      await InternalContractApi.updateInternalContract(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    contractNumber: undefined,
    signingCompany: undefined,
    counterpartyCompany: undefined,
    signatory: undefined,
    startDate: undefined,
    paymentDate: undefined,
    specialNotes: undefined,
    files: undefined,
    contractType: undefined,
    contractTitle: undefined,
    contractAmount: 0,
    signingDate: undefined,
    endDate: undefined,
    remarks: undefined,
    creatorName: undefined,
    updaterName: undefined,
  }
  formRef.value?.resetFields()
}
</script>
